package com.region.integral.common_user.obtain.dao.impl;

import java.util.List;

import org.springframework.stereotype.Component;

import com.region.integral.common_user.obtain.dao.IIntegralCommentGoods;
import com.region.integral.common_user.obtain.vo.IntegralData;
import com.region.integral.common_user.pojo.CUIEntity;
import com.region.integral.common_user.xml.Regulation;
import com.region.integral.common_user.xml.dto.CommentGoods;
import com.region.integral.exception.IntegralException;
import com.region.integral.hibernate.BaseHibernate;
import com.region.integral.util.XMLRegulationUtil;
@Component("iCommentGoods")
public class IntegralCommentGoodsImpl extends BaseHibernate implements
		IIntegralCommentGoods {

	@Override
	public void commentGoods(int userid,IntegralData integralData) throws IntegralException {
		
		CUIEntity cuiEntity = getCUIEntity(userid);
		if (cuiEntity != null) {
			int currIntegral = cuiEntity.getCurrIntegral();
			int maxIntegral = cuiEntity.getMaxIntegral();
			int commentGoodsNum = cuiEntity.getCommentGoodsNum();
			// 获取到积分规则 已换下面方式
			/*
			 * String ruleIntegral = RegulationUtil
			 * .getRuleIntegral(IntegralRuleConstants.COMMENT_GOODS); String[]
			 * rateAndIntegral = ruleIntegral.split(","); int rate =
			 * Integer.parseInt(rateAndIntegral[0]); int integral =
			 * Integer.parseInt(rateAndIntegral[1]);
			 */
			// 获取积分规则
			Regulation regulation = XMLRegulationUtil.unmarshaller();
			List<CommentGoods> commentGoods = regulation.getCommentgoods();
			for (CommentGoods cGoods : commentGoods) {
				// 判断频率后操作
				// 符合频率，加积分
				int rate = cGoods.getRate();
				int integral = cGoods.getIntegral();
				if (commentGoodsNum == 0) {
					int totalIntegral = currIntegral + integral;
					cuiEntity.setCurrIntegral(totalIntegral);
					if (maxIntegral < totalIntegral) {
						cuiEntity.setMaxIntegral(totalIntegral);
					}
					hibernateTemplate.update(cuiEntity);
					integralData.setSuccee(true);
					integralData.setObtainIntegral(integral);
					continue;
				}
				if (commentGoodsNum != 0 && commentGoodsNum % rate == 0) {
					int totalIntegral = currIntegral + integral;
					cuiEntity.setCurrIntegral(totalIntegral);
					if (maxIntegral < totalIntegral) {
						cuiEntity.setMaxIntegral(totalIntegral);
					}
					hibernateTemplate.update(cuiEntity);
					integralData.setSuccee(true);
					integralData.setObtainIntegral(integral);
					continue;
				}
			}
			cuiEntity.setCommentGoodsNum(commentGoodsNum + 1);
			hibernateTemplate.update(cuiEntity);
			
		}
	}
}
